package system;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.SQLException;
import java.sql.Statement;

// much of the code for this class is inspired by the code found at
// http://www.daniweb.com/software-development/java/threads/153923
public class 
SQLScriptRunner 
{	BufferedReader in = null;

	public SQLScriptRunner(String path)
	{	try {
			in = new BufferedReader(new FileReader(path));
		} catch (FileNotFoundException e) { e.printStackTrace(); } 
	}
	
	public String getNextStatement() 
		throws IOException
	{	String current = new String();
		String statement = new String();
		while( (current = in.readLine()) != null){
			if((current.length() > 0 && current.charAt(0) == '-') || current.length() == 0)
				continue;
			statement = statement + " " + current.trim();
			if(statement.charAt(statement.length()-1) == ';'){
				statement = statement.replace(';', ' ');
				return statement;
			}
		}
		return null;
	}

	public void 
	execute() 
	{	Statement stmnt = null;
	
		try 
		{	stmnt = OracleConnection.getInstance().getConnection().createStatement(); } 
		catch (SQLException e) { e.printStackTrace(); }
	
		String current = new String();
		try 
		{	while((current = getNextStatement()) != null){
				System.out.println(current.trim());
				try { stmnt.execute(current.trim()); }
				catch(SQLException e){ 
					System.err.println("Error");
					e.printStackTrace();
				};
			}
		} catch (IOException e) { e.printStackTrace(); }		
	}

}
